import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Typography, Table, Tag, Alert } from 'antd';
import { UserOutlined, ShoppingOutlined, AppstoreOutlined, DollarOutlined, WarningOutlined } from '@ant-design/icons';
import { statisticsService } from '../services/statisticsService';
import { furnitureService } from '../services/furnitureService';

const { Title } = Typography;

const Dashboard = () => {
  const [stats, setStats] = useState({
    userCount: 0,
    furnitureCount: 0,
    categoryCount: 0,
    totalValue: 0,
    averagePrice: 0,
    lowStockCount: 0,
  });
  const [recentFurniture, setRecentFurniture] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchDashboardData();
  }, []);

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 获取统计数据
      const [overviewRes, furnitureRes] = await Promise.all([
        statisticsService.getOverview(),
        furnitureService.getAllFurniture(),
      ]);

      const overview = overviewRes.data;
      const furniture = furnitureRes.data;

      setStats({
        userCount: overview.userCount,
        furnitureCount: overview.furnitureCount,
        categoryCount: overview.categoryCount,
        totalValue: overview.totalValue,
        averagePrice: overview.averagePrice,
        lowStockCount: overview.lowStockCount,
      });

      // 获取最近的家具（按ID排序，取前5个）
      const sortedFurniture = furniture
        .sort((a, b) => b.id - a.id)
        .slice(0, 5);
      setRecentFurniture(sortedFurniture);

    } catch (error) {
      console.error('获取仪表板数据失败:', error);
      setError('获取数据失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const recentFurnitureColumns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${price}`,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      render: (stock) => (
        <Tag color={stock > 10 ? 'green' : stock > 0 ? 'orange' : 'red'}>
          {stock}
        </Tag>
      ),
    },
  ];

  return (
    <div className="page-content">
      <div className="page-header">
        <Title level={2}>仪表板</Title>
      </div>

      {error && (
        <Alert
          message="数据加载失败"
          description={error}
          type="error"
          showIcon
          style={{ marginBottom: 24 }}
          action={
            <button onClick={fetchDashboardData} style={{ color: '#1890ff', cursor: 'pointer' }}>
              重试
            </button>
          }
        />
      )}

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="用户总数"
              value={stats.userCount}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="家具总数"
              value={stats.furnitureCount}
              prefix={<ShoppingOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="分类总数"
              value={stats.categoryCount}
              prefix={<AppstoreOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="库存总价值"
              value={stats.totalValue}
              prefix={<DollarOutlined />}
              precision={2}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 额外统计信息 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="平均价格"
              value={stats.averagePrice}
              prefix={<DollarOutlined />}
              precision={2}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="库存不足"
              value={stats.lowStockCount}
              prefix={<WarningOutlined />}
              valueStyle={{ color: stats.lowStockCount > 0 ? '#fa8c16' : '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 最近添加的家具 */}
      <Card title="最近添加的家具" className="card-container">
        <Table
          columns={recentFurnitureColumns}
          dataSource={recentFurniture}
          rowKey="id"
          loading={loading}
          pagination={false}
          size="small"
        />
      </Card>
    </div>
  );
};

export default Dashboard;
